<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入资源名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="资源状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择资源状态" clearable style="width: 150px">
          <el-option label="可用" value="1" />
          <el-option label="不可用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="显卡种类" prop="graphicsCardTypeName">
        <el-select v-model="queryParams.graphicsCardTypeName" placeholder="请选择显卡种类" clearable style="width: 180px">
          <el-option
            v-for="dict in dict.type.graphics_card_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用软件" prop="applicableSoftwareName">
        <el-select v-model="queryParams.applicableSoftwareName" placeholder="请选择适用软件" multiple clearable style="width: 260px">
          <el-option
            v-for="dict in dict.type.applicable_software"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 资源列表表格 -->
    <el-table v-loading="loading" :data="poolList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center" width="60">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="资源名称" align="center" prop="name" width="180"/>
      <el-table-column label="设备描述" align="center" prop="description" width="200" show-overflow-tooltip/>
      <el-table-column label="价格" align="center" prop="price" width="120"/>
      <el-table-column label="CPU" align="center" width="220">
        <template slot-scope="scope">
          {{ scope.row.cpu }}
          <span v-if="scope.row.cpuUnitName"> {{ scope.row.cpuUnitName }}</span>
          <span v-if="scope.row.cpuTypeName"> {{ scope.row.cpuTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内存" align="center" width="220">
        <template slot-scope="scope">
          {{ scope.row.memory }}
          <span v-if="scope.row.memoryUnit"> {{ scope.row.memoryUnit }}</span>
          <span v-if="scope.row.memoryTypeName"> {{ scope.row.memoryTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="基础存储" align="center" width="240">
        <template slot-scope="scope">
          {{ scope.row.storage }}
          <span v-if="scope.row.storageUnit"> {{ scope.row.storageUnit }}</span>
          <span v-if="scope.row.storageTypeName"> {{ scope.row.storageTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显卡种类" align="center" prop="graphicsCardTypeName" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.graphicsCardTypeName">{{ scope.row.graphicsCardTypeName }}</span>
          <template v-else>
            <dict-tag :options="dict.type.graphics_card_type" :value="scope.row.graphicsCardType" />
          </template>
        </template>
      </el-table-column>
      <el-table-column label="适用软件" align="center" prop="applicableSoftwareName" width="240" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.applicableSoftwareName" style="display: flex; flex-wrap: wrap; gap: 4px;">
            <el-tag v-for="software in scope.row.applicableSoftwareName.split(',')" :key="software" size="small" type="info">
              {{ software }}
            </el-tag>
          </div>
          <template v-else>
            <div v-if="scope.row.applicableSoftware" style="display: flex; flex-wrap: wrap; gap: 4px;">
              <el-tag v-for="software in scope.row.applicableSoftware.split(',')" :key="software" size="small" type="info">
                {{ selectDictLabels(dict.type.applicable_software, software) }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left" style="padding: 20px;">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="资源名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资源名称" style="width: 280px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">可用</el-radio>
                <el-radio :label="0">不可用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="价格(/h)" prop="price">
              <el-input-number v-model="form.price" placeholder="请输入价格" :precision="2" :min="0" style="width: 280px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="CPU" prop="cpu">
              <el-input-number v-model="form.cpu" :min="0" placeholder="核数" style="width: 140px; display: inline-block;" />
              <el-select v-model="form.cpuUnitName" placeholder="单位" style="width: 120px; display: inline-block; margin-left: 10px;">
                <el-option
                  v-for="dict in dict.type.pool_cpu_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
              <el-select v-model="form.cpuType" placeholder="CPU类型" style="width: 140px; display: inline-block; margin-left: 10px;">
                <el-option
                  v-for="dict in dict.type.pool_cpu"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="内存" prop="memory">
              <el-input-number v-model="form.memory" :min="0" placeholder="大小" style="width: 140px; display: inline-block;" />
              <el-select v-model="form.memoryUnit" placeholder="单位" style="width: 100px; display: inline-block; margin-left: 10px;">
                <el-option label="GB" value="GB" />
                <el-option label="TB" value="TB" />
              </el-select>
              <el-select v-model="form.memoryType" placeholder="内存类型" style="width: 160px; display: inline-block; margin-left: 10px;">
                <el-option
                  v-for="dict in dict.type.pool_run_memory"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础存储" prop="storage">
              <el-input-number v-model="form.storage" :min="0" placeholder="大小" style="width: 140px; display: inline-block;" />
              <el-select v-model="form.storageUnit" placeholder="单位" style="width: 100px; display: inline-block; margin-left: 10px;">
                <el-option label="GB" value="GB" />
                <el-option label="TB" value="TB" />
              </el-select>
              <el-select v-model="form.storageType" placeholder="硬盘类型" style="width: 160px; display: inline-block; margin-left: 10px;" filterable>
                <el-option
                  v-for="dict in dict.type.pool_hard_disk"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="显卡种类" prop="graphicsCardType">
              <el-select v-model="form.graphicsCardType" placeholder="请选择显卡种类" style="width: 280px;">
                <el-option
                  v-for="dict in dict.type.graphics_card_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用软件" prop="applicableSoftware">
              <el-select v-model="form.applicableSoftware" placeholder="请选择适用软件" multiple style="width: 280px;">
                <el-option
                  v-for="dict in dict.type.applicable_software"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入设备描述" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资源图片" prop="imageUrl">
              <image-upload v-model="form.imageUrl" :limit="1" :fileSize="10" action="/system/file/upload"></image-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入API方法
import { listPool, savePool, deletePool } from '@/api/official/pool'
// 导入字典相关方法
import { getDicts } from '@/api/system/dict/data'
import { selectDictLabels } from '@/utils/ruoyi'
// 导入自定义组件
import ImageUpload from '@/components/ImageUpload'
import DictTag from '@/components/DictTag'

export default {
  name: "Pool",
  components: {
    ImageUpload,
    DictTag
  },
  dicts: ['applicable_software', 'graphics_card_type', 'pool_cpu', 'pool_run_memory', 'pool_hard_disk', 'pool_cpu_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源列表数据
      poolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        graphicsCardTypeName: undefined,
        applicableSoftwareName: []
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        description: undefined,
        price: 0,
        cpu: undefined,
        cpuUnit: undefined,
        cpuUnitName: undefined,
        cpuType: undefined,
        memory: undefined,
        memoryUnit: 'GB',
        memoryType: undefined,
        storage: undefined,
        storageUnit: 'GB',
        storageType: undefined,
        applicableSoftware: [],
        graphicsCardType: undefined,
        imageUrl: undefined,
        status: 1
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "资源名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        cpu: [
          { required: true, message: "CPU不能为空", trigger: "blur" }
        ],
        memory: [
          { required: true, message: "内存不能为空", trigger: "blur" }
        ],
        storage: [
          { required: true, message: "存储不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "设备描述不能为空", trigger: "blur" }
        ],
        graphicsCardType: [
          { required: true, message: "显卡种类不能为空", trigger: "change" }
        ],
        applicableSoftware: [
          { required: true, message: "适用软件不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询资源列表 */
    getList() {
      this.loading = true
      console.log('开始查询资源列表', this.queryParams)

      // 实际API调用
      const params = { ...this.queryParams }
      if (Array.isArray(params.applicableSoftwareName)) {
        params.applicableSoftwareName = params.applicableSoftwareName.join(',')
      }
      listPool(params).then(response => {
        console.log('查询结果', response)
        // 确保正确处理响应数据格式
        this.$set(this, 'poolList', response.rows || [])
        this.$set(this, 'total', response.total || 0)
        console.log('处理后的数据', this.poolList)
      }).catch(error => {
        console.error('查询失败', error)
      }).finally(() => {
        this.loading = false
      })

      // 如果API调用失败，可以使用下面的mock数据进行测试
      /*
      const mockData = {
        "total": 1,
        "rows": [
            {
                "id": "55ed3426095b7614e156e22bbd307adc",
                "createBy": 1,
                "createTime": "2025-09-07 17:26:13",
                "updateBy": 1,
                "updateTime": "2025-09-07 17:26:13",
                "remark": null,
                "name": "NVIDIA V100 服务器",
                "description": "高性能计算服务器",
                "price": 12,
                "cpu": "32核 Intel Xeon",
                "memory": 128,
                "storage": 500,
                "applicableSoftware": "VASP,Amber",
                "graphicsCardType": "V100",
                "imageUrl": "/profile/upload/2025/09/07/headImg_20250907172544A001.jpg",
                "status": 1
            }
        ],
        "code": 200,
        "msg": "查询成功"
      };

      setTimeout(() => {
        this.$set(this, 'poolList', mockData.rows || [])
        this.$set(this, 'total', mockData.total || 0)
        console.log('使用mock数据', this.poolList)
        this.loading = false
      }, 100)
      */
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        description: undefined,
        price: 0,
        cpu: undefined,
        cpuUnit: undefined,
        cpuUnitName: undefined,
        cpuType: undefined,
        memory: undefined,
        memoryUnit: 'GB',
        memoryType: undefined,
        storage: undefined,
        storageUnit: 'GB',
        storageType: undefined,
        applicableSoftware: [],
        graphicsCardType: undefined,
        imageUrl: undefined,
        status: 1
      }
      // 默认CPU单位取字典第一项（使用名称）
      if (this.dict && this.dict.type && this.dict.type.pool_cpu_unit && this.dict.type.pool_cpu_unit.length > 0) {
        this.form.cpuUnitName = this.dict.type.pool_cpu_unit[0].label
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.graphicsCardTypeName = undefined
      this.queryParams.applicableSoftwareName = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加资源"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 处理多选字段
      if (row.applicableSoftware && typeof row.applicableSoftware === 'string') {
        row.applicableSoftware = row.applicableSoftware.split(',')
      }

      const cloned = { ...row }

      // 根据 Name 字段回显字典型下拉框（若后端未返回值字段）
      const findValueByLabel = (options, label) => {
        if (!options || !label) return undefined
        const opt = options.find(o => String(o.label) === String(label))
        return opt ? opt.value : undefined
      }

      // CPU类型
      if (!cloned.cpuType && cloned.cpuTypeName) {
        cloned.cpuType = findValueByLabel(this.dict.type.pool_cpu, cloned.cpuTypeName)
      }
      // CPU单位（若仅返回名称，直接用于回显；若返回值则转名称）
      if (!cloned.cpuUnitName && cloned.cpuUnit) {
        const opt = (this.dict.type.pool_cpu_unit || []).find(o => String(o.value) === String(cloned.cpuUnit))
        if (opt) cloned.cpuUnitName = opt.label
      }
      // 内存类型
      if (!cloned.memoryType && cloned.memoryTypeName) {
        cloned.memoryType = findValueByLabel(this.dict.type.pool_run_memory, cloned.memoryTypeName)
      }
      // 硬盘类型
      if (!cloned.storageType && cloned.storageTypeName) {
        cloned.storageType = findValueByLabel(this.dict.type.pool_hard_disk, cloned.storageTypeName)
      }
      // 显卡种类
      if (!cloned.graphicsCardType && cloned.graphicsCardTypeName) {
        cloned.graphicsCardType = findValueByLabel(this.dict.type.graphics_card_type, cloned.graphicsCardTypeName)
      }
      // 适用软件（名称转值数组）
      if ((!cloned.applicableSoftware || cloned.applicableSoftware.length === 0) && cloned.applicableSoftwareName) {
        const names = String(cloned.applicableSoftwareName).split(',').map(s => s.trim()).filter(Boolean)
        const values = []
        names.forEach(n => {
          const v = findValueByLabel(this.dict.type.applicable_software, n)
          if (v !== undefined && v !== null && v !== '') values.push(v)
        })
        cloned.applicableSoftware = values
      }

      this.form = { ...cloned }
      this.open = true
      this.title = "修改资源"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理多选字段
          const submitData = { ...this.form }
          if (Array.isArray(submitData.applicableSoftware)) {
            submitData.applicableSoftware = submitData.applicableSoftware.join(',')
          }

          // 后端不需要单位字段：cpuUnit（单位前端固定展示）
          if ('cpuUnit' in submitData) {
            delete submitData.cpuUnit
          }

          // 辅助方法：根据字典value取label
          const getLabel = (options, value) => {
            if (!options || value === undefined || value === null || value === '') return undefined
            const opt = options.find(o => String(o.value) === String(value))
            return opt ? opt.label : undefined
          }

          // 字典名称派生字段
          submitData.cpuTypeName = getLabel(this.dict.type.pool_cpu, submitData.cpuType)
          // CPU单位名称优先使用已选名称，其次由值反查
          submitData.cpuUnitName = submitData.cpuUnitName || getLabel(this.dict.type.pool_cpu_unit, submitData.cpuUnit)
          submitData.memoryTypeName = getLabel(this.dict.type.pool_run_memory, submitData.memoryType)
          submitData.storageTypeName = getLabel(this.dict.type.pool_hard_disk, submitData.storageType)
          submitData.graphicsCardTypeName = getLabel(this.dict.type.graphics_card_type, submitData.graphicsCardType)
          // 适用软件（多选）名称，按逗号拼接
          submitData.applicableSoftwareName = submitData.applicableSoftware
            ? this.selectDictLabels
              ? this.selectDictLabels(this.dict.type.applicable_software, submitData.applicableSoftware, ',')
              : (submitData.applicableSoftware.split(',')
                  .map(v => getLabel(this.dict.type.applicable_software, v))
                  .filter(Boolean)
                  .join(','))
            : undefined

          // 仅传 Name，不传 Type 值字段与 applicableSoftware 值
          if ('cpuType' in submitData) delete submitData.cpuType
          if ('cpuUnit' in submitData) delete submitData.cpuUnit
          if ('memoryType' in submitData) delete submitData.memoryType
          if ('storageType' in submitData) delete submitData.storageType
          if ('graphicsCardType' in submitData) delete submitData.graphicsCardType
          if ('applicableSoftware' in submitData) delete submitData.applicableSoftware

          savePool(submitData).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除资源编号为"' + ids + '"的数据项？').then(() => {
        return deletePool(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.el-table .el-table-column {
  text-align: center;
}

.dialog-footer {
  text-align: center;
}

/* 固定字段区域样式 */
.fixed-fields-section {
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

/* 动态字段样式 */
.dynamic-fields {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 区域标题样式 */
.section-title,
.fields-section-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
}

/* 表单元素间距优化 */
.el-form-item {
  margin-bottom: 18px;
}

/* 对话框整体优化 */
.el-dialog__body {
  padding: 20px;
}

/* 确保输入框、数字输入框和选择器样式一致 */
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
</style>
